/*
 * 文件名：RealStreamPassivSenderServer.java
 * 版权：亚信联创版权所有
 * 描述：TODO
 * 修改人：yuanze
 * 修改时间：2014年11月13日
 * 修改内容：TODO
 */
package com.ailk.bigdata.etl.realstream.server.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ailk.bigdata.etl.realstream.server.netty.handler.RealStreamDataEncode;

/**
 * @description 实时流被动发送模式
 * @author [yuanze]
 * @version [版本号,2014年11月13日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class RealStreamPassivSenderServer
{
	private static final Logger logger = LoggerFactory.getLogger(RealStreamPassivSenderServer.class);
	private static final StringDecoder DECODER = new StringDecoder();
	private int port;

	public RealStreamPassivSenderServer(int port)
	{
		this.port = port;
	}

	public void run(final ChannelInboundHandlerAdapter sendHandler) throws Exception
	{
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try
		{
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
					.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_SNDBUF, 1048576 * 4).handler(new LoggingHandler(LogLevel.ERROR))
					.childHandler(new ChannelInitializer<SocketChannel>()
					{
						@Override
						public void initChannel(SocketChannel ch) throws Exception
						{
							ChannelPipeline pipeline = ch.pipeline();
							pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192 * 4, Delimiters.lineDelimiter()));
							pipeline.addLast("encoder", new RealStreamDataEncode());
							pipeline.addLast("decoder", DECODER);
							pipeline.addLast(sendHandler);
						}
					});
			b.bind(port).sync().channel().closeFuture().sync();
		}
		catch (Exception e)
		{
			logger.error("开启监听失败！端口[" + port + "]", e);
			throw e;
		}
		finally
		{
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
